#!/bin/bash
set -e

SCRIPT_DIR=$(realpath $(dirname "$0"))
CURRENT_DIR=$(realpath $(pwd))

WORKDIR=$CURRENT_DIR

source $SCRIPT_DIR/common.sh

function repod_init()
{
    local rpmd=$(realpath $1)

    [[ -d "$rpmd/.repodata/" ]] && rm -rf "$rpmd/.repodata/"
    createrepo -d -o $rpmd $rpmd || log_error "init repo failed" || return 1
}

function repod_update()
{
    local rpmd=$(realpath $1)

    [[ -d "$rpmd/.repodata/" ]] && rm -rf "$rpmd/.repodata/"
    createrepo --update $rpmd || log_error "update repo failed" || return 1
}

function usage()
{
    log_info "Usage: ./$(basename $0) init|update -d [dir]"
}

function param_parse()
{
    OPER=$1
    ( [[ x$OPER != x"init" ]] && [[ x$OPER != x"update" ]] ) && usage && return 1
    shift

    while getopts "d:" opt
    do
        case "$opt" in
            d)
            WORKDIR="$OPTARG";;
            ?)
            log_error "unknown parameters" && usage && return 1;;
        esac
    done

    [[ ! -n $WORKDIR ]] && log_error "empty parameter, -d" && usage && return 1
    [[ ! -d $WORKDIR ]] && log_error "destdir not exist" && usage && return 1

    return 0
}

function main()
{
    param_parse $@

    if [[ $OPER = "init" ]]
    then
        repod_init $WORKDIR
    elif [[ $OPER = "update" ]]
    then
        repod_update $WORKDIR
    else
        return 1
    fi
}

main $@

